# -*- coding: UTF-8 -*-
"""
@author: tgy
@file: video.py
@time: 2021/05/30
"""
import os

class Video:
    ...

    def mp4_to_flv(self, mp4_file_path: str, flv_file_path: str, crf=19):
        ...
        if crf < 19:
            crf = 19
        # ffmpeg -i 22-播放器完善与H264视频编码.mp4 -c:v libx264 -crf 19 22-播放器完善与H264视频编码.flv
        command = f'ffmpeg -i {mp4_file_path} -c:v libx264 -crf {crf} {flv_file_path}'
        os.system(command)

    def mp4_join(self, mp4_files_path, last_file_path):
        ...
        file_names = []
        for mp4_file in os.listdir(mp4_files_path):
            ...
            if os.path.isfile(os.path.join(mp4_files_path, mp4_file)) and mp4_file.endswith('mp4'):
                ...
                file_names.append(mp4_file)

        if not file_names:
            return False

        file_names = sorted(file_names)
        print(file_names)

        new_names = {}
        names_file_name = 'names_list.txt'
        names_file_path = os.path.join(mp4_files_path, names_file_name)
        names_list_file = open(names_file_path, mode='w')

        for index, file_name in enumerate(file_names, start=1):
            ...
            new_name = str(index) + '.mp4'
            new_names[new_name] = file_name
            os.renames(os.path.join(mp4_files_path, file_name), os.path.join(mp4_files_path, new_name))
            names_list_file.write('file ' + new_name + '\n')
        names_list_file.close()

        try:
            # command = f'ffmpeg -i {names_file_path} -c:v libx264 -crf 19 {last_file_path}'
            command = f'ffmpeg -f concat -i {names_file_path} -c copy {last_file_path}'
            print(command)
            os.system(command)
        except Exception as e:
            print(e)
            return False
        if os.path.exists(names_file_path):
            ...
            os.unlink(names_file_path)

        for new_name, old_name in new_names.items():
            ...
            os.renames(os.path.join(mp4_files_path, new_name), os.path.join(mp4_files_path, old_name))
        return True

def join_and_conver():
    ...
    mp4_files_path = '/Users/tgy/Downloads/04-FFmpeg命令实战-高屋建瓴2'
    out_file_name = 'ffmpeg命令介绍'
    mp4_join_file_name = f'{out_file_name}.mp4'
    mp4_join_file_path = os.path.join(mp4_files_path, mp4_join_file_name)
    flv_file_path = os.path.join(mp4_files_path, out_file_name + ".flv")
    video = Video()
    if video.mp4_join(mp4_files_path, mp4_join_file_path):
        ...
        video.mp4_to_flv(mp4_join_file_path, flv_file_path)

def mp4_to_flv():
    ...
    video = Video()
    video.mp4_to_flv("/Users/tgy/Documents/c++/37-centos安装nignx和rtmp.mp4",
                     "/Users/tgy/Documents/c++/37-centos安装nignx和rtmp.flv")

if __name__ == '__main__':
    pass
    # join_and_conver()
    # mp4_to_flv()
    import tempfile
    file = tempfile.TemporaryFile()
    file.write("asd".encode('utf8'))
    file.seek(0)
    print(file.read())



